/**
 * 关于网上存储pinia state某个值 pinia-plugin-persistedstate 网上一堆答案都是设置paths的，经过查询最新4.2.0文档，该属性为3版本的属性，最新文本paths已替换为pick。如果发现设置的paths还是存储的所有值，请检查版本，并替换为pick，就ok了。
————————————————

                            版权声明：本文为博主原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接和本声明。
                        
原文链接：https://blog.csdn.net/texvview/article/details/145120507
 */
import { defineStore } from 'pinia';
import pinia from '@/store';
import { userLogin, refreshUserInfo } from '@/api/user';
import { UserState, LoginRequest } from './types';

// 定义持久化配置
const persistConfig = {
    key: 'userInfo',
    storage: sessionStorage,
    pick: ['accessToken', 'refreshToken', 'roles', 'username']
};

export const useUserStoreHook = defineStore('userInfo', {
    state: (): UserState => ({
        username: '前端',
        accessToken: '',
        refreshToken: '',
        roles: ['common']
    }),
    getters: {},
    actions: {
        storeUserLogin(data: LoginRequest) {
            return userLogin(data).then((res) => {
                this.username = res.username;
                this.roles = res.roles;
                this.accessToken = res.accessToken;
                return res;
            });
        },
        storeRefreshUserInfo() {
            // 修正拼写错误
            if (this.username === 'admin' && this.accessToken !== '') {
                return refreshUserInfo({ accessToken: this.accessToken })
                    .then((res) => {
                        this.username = res.username;
                        this.roles = res.roles;
                        this.accessToken = res.accessToken;
                    })
                    .catch(() => {
                        this.accessToken = '';
                    });
            }
        }
    },
    persist: persistConfig // 正确配置持久化
});

export function useUserStore() {
    return useUserStoreHook(pinia);
}
